<template>
  <el-row :gutter="20">
    <el-col :span="4">
      <category @tree-node-click="treeNodeClick"></category>
    </el-col>
    <el-col :span="19">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="属性名" prop="attrName">
          <el-input
            v-model="queryParams.attrName"
            placeholder="请输入属性名"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['product:attr:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['product:attr:edit']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['product:attr:remove']"
          >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['product:attr:export']"
          >导出
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="attrList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="属性id" align="center" prop="attrId"/>
        <el-table-column label="属性名" align="center" prop="attrName"/>
        <el-table-column label="是否检索" align="center" prop="searchType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.product_need_search" :value="scope.row.searchType"/>
          </template>
        </el-table-column>
        <el-table-column label="值类型" align="center" prop="valueType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.product_value_type" :value="scope.row.valueType"/>
          </template>
        </el-table-column>
        <el-table-column label="属性图标" align="center" prop="icon">
          <template slot-scope="scope">
            <svg-icon :icon-class="scope.row.icon"/>
          </template>
        </el-table-column>
        <el-table-column label="可选值列表" align="center" prop="valueSelect">
          <template slot-scope="scope">
            <el-tooltip placement="top">
              <div slot="content">
                <span v-for="(i,index) in scope.row.valueSelect.split(';')" :key="index">{{i}}<br/></span>
              </div>
              <el-tag>{{scope.row.valueSelect.split(";")[0]+" ..."}}</el-tag>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="属性类型" align="center" prop="attrType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.product_attr_type" :value="scope.row.attrType"/>
          </template>
        </el-table-column>
        <el-table-column label="启用状态" align="center" prop="enable">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.product_disable_normal" :value="scope.row.enable"/>
          </template>
        </el-table-column>
        <el-table-column label="所属分类" align="center" prop="category.name"/>
        <el-table-column label="快速展示" align="center" prop="showDesc">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.product_yes_no" :value="scope.row.showDesc"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['product:attr:edit']"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['product:attr:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改商品属性对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="88px">
          <el-form-item label="属性名" prop="attrName">
            <el-input v-model="form.attrName" placeholder="请输入属性名"/>
          </el-form-item>
          <el-form-item label="是否检索" prop="searchType">
            <el-select v-model="form.searchType" placeholder="请选择是否检索">
              <el-option
                v-for="dict in dict.type.product_need_search"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="值类型" prop="valueType">
            <el-select v-model="form.valueType" placeholder="请选择值类型">
              <el-option
                v-for="dict in dict.type.product_value_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="属性图标" prop="icon">
            <!--<el-input v-model="form.icon" placeholder="请输入属性图标" />-->
            <el-popover
              placement="bottom-start"
              width="460"
              trigger="click"
              @show="$refs['iconSelect'].reset()"
            >
              <IconSelect ref="iconSelect" @selected="selected"/>
              <el-input slot="reference" v-model="form.icon" placeholder="点击选择图标" readonly>
                <svg-icon
                  v-if="form.icon"
                  slot="prefix"
                  :icon-class="form.icon"
                  class="el-input__icon"
                  style="height: 32px;width: 16px;"
                />
                <i v-else slot="prefix" class="el-icon-search el-input__icon"/>
              </el-input>
            </el-popover>
          </el-form-item>
          <el-form-item label="可选值列表" prop="valueSelect">
            <el-select
              v-model="form.valueSelect"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择文章标签[用逗号分隔]">
              <el-option
                v-for="item in valueOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <!--<el-input v-model="form.valueSelect" placeholder="请输入可选值列表[用逗号分隔]" />-->
          </el-form-item>
          <el-form-item label="属性类型" prop="attrType">
            <el-select v-model="form.attrType" placeholder="请选择属性类型" disabled>
              <el-option
                v-for="dict in dict.type.product_attr_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="启用状态" prop="enable">
            <el-select v-model="form.enable" placeholder="请选择启用状态">
              <el-option
                v-for="dict in dict.type.product_disable_normal"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属分类" prop="categoryId">
            <el-cascader style="width: 380px"
                         v-model="form.categoryId"
                         :options="categoryOptions" :props="categoryProps" @change="categoryChange"></el-cascader>
            <!--<el-input v-model="form.categoryId" placeholder="请输入所属分类" />-->
          </el-form-item>
          <el-form-item label="快速展示" prop="showDesc">
            <el-select v-model="form.showDesc" placeholder="请选择快速展示">
              <el-option
                v-for="dict in dict.type.product_yes_no"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </el-col>
  </el-row>

</template>

<script>
import {addAttr, delAttrIds, getAttr, listAttr, updateAttr} from "@/api/product/attr";
import {listAttrgroup} from "@/api/product/attrgroup";
import {listCategory} from "@/api/product/category";
import Category from "../../components/category";
import IconSelect from "@/components/IconSelect";

export default {
    name: "Attr",
    dicts: ['product_attr_type', 'product_disable_normal', 'product_need_search', 'product_yes_no', 'product_value_type'],
    components: {Category, IconSelect},
    data() {
      return {
        valueOptions: [],
        categoryProps:
          {
            value: 'catId',
            label: 'name',
            children: 'children'
          },
        categoryOptions: [],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        idGroups: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 商品属性表格数据
        attrList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          attrName: null,
          categoryId: null,
        },
        attrgroupList: [],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          attrName: [
            {required: true, message: "属性名不能为空", trigger: "blur"}
          ],
          searchType: [
            {required: true, message: "是否检索不能为空", trigger: "change"}
          ],
          valueType: [
            {required: true, message: "值类型不能为空", trigger: "change"}
          ],
          attrType: [
            {required: true, message: "属性类型不能为空", trigger: "change"}
          ],
          categoryId: [
            {required: true, message: "分类编号不能为空", trigger: "change"}
          ]

        }
      };
    },
    created() {
      // 获取基本属性列表
      this.getList();
      // 获取分类树
      this.getCategories();
    },
    methods: {
      // 选择图标
      selected(name) {
        this.form.icon = name;
      },
      treeNodeClick(data, node, component) {
        //console.log(data,node,component)
        if (node.level == 3) {
          this.queryParams.categoryId = data.catId;
          this.getList();
        }
      },
      // 分类树值改变时，获取对应的分组信息
      categoryChange(value) {
        let categoryId = value[value.length - 1];
        this.getGroup(categoryId);
      },
      // 获取分组信息
      getGroup(categoryId) {
        let queryParams = {
          pageNum: 1,
          pageSize: 1000000,
          categoryId: categoryId,
        };
        listAttrgroup(queryParams).then(response => {
          this.attrgroupList = response.data.records;
        });
      },
      getCategories() {
        listCategory().then(response => {
          this.categoryOptions = this.handleTree(response.data, "catId", "parentCid");
        });
      },
      /** 查询商品属性列表 */
      getList() {
        this.loading = true;
        this.queryParams.attrType=0;
        listAttr(this.queryParams).then(response => {
          this.attrList = response.data.records;
          this.total = response.data.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          attrId: null,
          attrName: null,
          searchType: null,
          valueType: null,
          icon: null,
          valueSelect: null,
          attrType: null,
          enable: null,
          categoryId: null,
          showDesc: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams.categoryId = undefined;
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
       /* this.idGroups = [];
        this.ids = selection.map(item => item.attrId)
        selection.forEach(item => {
          let obj = {};
          obj.attrId = item.attrId;
          obj.groupId = item.group.attrGroupId;
          this.idGroups.push(obj);
        });
        this.single = selection.length !== 1
        this.multiple = !selection.length*/
        this.ids = selection.map(item => item.attrId)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.form.attrType = 0;
        this.open = true;
        this.title = "添加规则参数";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const attrId = row.attrId || this.ids;
        getAttr(attrId).then(response => {
          this.getGroup(response.data.categoryId);
          this.form = response.data;
          this.form.valueSelect = this.form.valueSelect.split(";");
          this.open = true;
          this.title = "添加规则参数";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.attrId != null) {
              let oldValueSelect = this.form.valueSelect;
              this.form.valueSelect = this.form.valueSelect.join(";");
              updateAttr(this.form).then(response => {
                if (response.success) {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.$modal.msgError(response.msg);
                  this.form.valueSelect = oldValueSelect;
                }
              });
            } else {
              let oldCategoryId = this.form.categoryId;
              let oldValueSelect = this.form.valueSelect;
              this.form.categoryId = this.form.categoryId[this.form.categoryId.length - 1];
              this.form.valueSelect = this.form.valueSelect.join(";");
              addAttr(this.form).then(response => {
                if (response.success) {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.$modal.msgError(response.msg);
                  this.form.categoryId = oldCategoryId;
                  this.form.valueSelect = oldValueSelect;
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {

        const attrIds = row.attrId || this.ids;
        this.$modal.confirm('是否确认删除销售属性编号为"' + attrIds + '"的数据项？').then(function () {
          return delAttrIds(attrIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});

      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('product/attr/export', {
          ...this.queryParams
        }, `attr_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>

<style scoped>
  .el-row {
    left: 20px;
    /*top: 20px;*/
    margin-top: 20px;
  }

  .el-select {
    width: 380px;
  }

  .el-input {
    width: 380px;
  }

</style>
